package com.wen.springbootdistributionserver.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.tools.json.JSONUtil;
import com.wen.springbootdistributionserver.pojo.Orders;
import com.wen.springbootdistributionserver.service.DispatchService;
import com.wen.springbootdistributionserver.util.JsonUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;

@Service
public class OrderMqConsumer {

    @Autowired
    private DispatchService dispatchService;

    private int count = 1;

    /**
     * 控制消息重试的机制：
     * 1 ，配置重试次数(修改配置文件)
     * 2、try catch + basicNack(与方法1冲突)
     * 3、try catch + basicNack + 死信队列
     */
    @RabbitListener(queues = {"order.queue"})
    public void messageConsumer(String orderMsg, Channel channel, CorrelationData correlationData, @Header(AmqpHeaders.DELIVERY_TAG) long tag)throws Exception{

        try{
            //接收到队列的消息
            System.out.println("收到的mq消息："+ orderMsg + ",count="+ count++);
            Orders order = JsonUtils.jsonToPojo(orderMsg,Orders.class);
            String orderId = order.getOrderId();
            //派单处理
            dispatchService.dispatch(orderId);
            System.err.println(1/0);
            channel.basicAck(tag,false);
        }catch (Exception e){
            System.err.println("-----接收mq消息出错啦------");
            //重发一次后，丢失、还是日志、存库根据自己的业务场景去决定。
            //参数1：消息的tag,参数2：false 多条处理，参数3：重发
            channel.basicNack(tag,false,false);
        }

    }

}
